﻿# -*- coding:utf-8 -*-
#
# склад
#
import datetime
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.template import RequestContext, Context
from django.core.urlresolvers import reverse
from django.db.models import Sum, Count

from sklad.forms import CategoryForm, PartForm  #, DocumentForm, DocumentReceiptForm, DocumentDeliveryForm Max, Min, Avg, 
from sklad.models import Category, Part, DocumentReceipt, DocumentDelivery, Unit, Waybill
from shm.models import Department

from sklad.contextprocessors import category_proc



@login_required
@permission_required('sklad.change_part')
def edit(request, partid):
    part_inst = Part.objects.get(id=partid)
    if request.method == 'POST':
        form = PartForm(request.POST, request.FILES, instance=part_inst)
        if form.is_valid():
            part=form.save(commit=False)
            part.user=request.user
            part.save()
            return HttpResponseRedirect(reverse('category_view', args=[(request.session["current_category"])])) 
    else:
        form = PartForm(instance=part_inst)
    return render_to_response('sklad/form_part_edit.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))



@login_required
@permission_required('sklad.add_part')
def create(request):
    if request.method == 'POST':
        form = PartForm(request.POST, request.FILES)
        if form.is_valid():
            part=form.save(commit=False)
            part.user=request.user
            part.save()
            return HttpResponseRedirect(reverse('category_view', args=[(request.session["current_category"])]))
    else:
        form = PartForm(initial={'category': request.session["current_category"]})
    return render_to_response('sklad/form_part_add.html', {'form' : form}, context_instance=RequestContext(request, processors=[category_proc]))



@login_required
@permission_required('sklad.delete_part')
def delete(request, item):
    pass
    
    
    
@login_required
@permission_required('sklad.view_part')    
def detail(request, part_id):    
    part = get_object_or_404(Part, id = part_id)
    category = part.category
    #
    receipts = Waybill.objects.filter(part=part, doc='rec')
    deliverys = Waybill.objects.filter(part=part, doc='del')
    #
    count = Waybill.objects.filter(part=part).aggregate(Sum("count"))
    request.session["current_category"] = int(category.id)
    context = Context({
      'category' : category,
      'part' : part,
      'receipts':receipts,
      'deliverys':deliverys,
      'count':count,
    })
    return render_to_response('sklad/part_detail.html', context, context_instance=RequestContext(request, processors=[category_proc]))



@login_required   
@permission_required('sklad.view_part')  
def serials(request, part_id):    
    part = get_object_or_404(Part, id = part_id)
    category = part.category
    serials = PartItem.objects.select_related().filter(part=part_id, document_state='R')  
    
    if request.method == 'POST':
        if request.POST.has_key('save_serials'): 
            print "button _save_serials_ pressed..."  
            if request.POST.has_key('serials'):
                change_serials = [v for v in request.POST.getlist('serials') if v != '']
                print change_serials

        if request.POST.has_key('delivery_serials'): 
            print "button _delivery_serials_ pressed..."  
            if request.POST.has_key('selected_serial'):
                selected_serial = [v for v in request.POST.getlist('selected_serial') if v != '']
                print selected_serial
           
    context = Context({
      'category' : category,
      'part' : part,
      'serials':serials,  
    })
    return render_to_response('part_serial.html', context, context_instance=RequestContext(request, processors=[category_proc]))

    